<template>
    <div class="system-auth-container">
        <el-form :inline="true" ref="form" class="system-search-form" :model="searchForm">
            <el-form-item>
                <el-cascader
                    class="go-out"
                    v-model="searchForm.mechanism"
                    :options="mechanismList"
                    :show-all-levels="false"
                    :props="{ checkStrictly: true, emitPath: false }"
                    filterable
                    size="small">
                </el-cascader>
            </el-form-item>
            <el-form-item>
                <el-input type="text" maxlength="100" v-model="searchForm.name" @keyup.enter.native="toFirstPage()" placeholder="角色名称" size="small"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button class="sub-btn" type="primary" size="small" @click="toFirstPage()">查询</el-button>
            </el-form-item>
        </el-form>
        <div class="table-box">
            <el-button class="add-btn" type="primary" size="small" icon="el-icon-plus" v-auth="{code: 300003000001}" @click="showAddDialog">新增</el-button>
            <el-table
                ref="tableData"
                :data="tableData"
                tooltip-effect="light"
                border
                :max-height="tableHeight"
                @sort-change="sortChange"
                class="data-table">
                <el-table-column
                    label="序号"
                    type="index"
                    align="center"
                    width="50">
                </el-table-column>
                <el-table-column
                    prop="name"
                    align="center"
                    label="角色名称"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="createdName"
                    align="center"
                    label="创建人"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="createdTime"
                    align="center"
                    label="创建时间"
                    sortable="custom"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{parseTime(new Date(scope.row.createdTime).getTime())}}
                    </template>
                </el-table-column>
                <el-table-column
                    label="启/停"
                    align="center"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.state" size="small" :disabled="!showBtnAuth(300003000002)" @change="toChangeState(scope.$index, scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-button type="text" size="small" v-auth="{code: 300003000002}" @click="tableEdit(scope.row)">
                            编辑
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableData.length > 0" :total="total" :page.sync="currentPage" :limit.sync="pageSize"
                        @pagination="getData"/>
        </div>
        <el-dialog
            :title="isAdd ? '新增角色权限' : '编辑角色权限'"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            center
            width="40%"
            @close="closeDialog">
            <el-form :inline="true" ref="dialogForm" class="dialog-form dialog-form-auth" :rules="editFormRules" :model="editForm" label-width="80px">
                <el-form-item label="名称" prop="name">
                    <el-input type="text" v-model="editForm.name" maxlength="100" placeholder="请输入角色名称" size="small"></el-input>
                </el-form-item>
                <el-form-item label="角色类型" prop="type">
                    <el-radio-group v-model="editForm.type">
                        <el-radio :label="1">临床</el-radio>
                        <el-radio :label="2">病案</el-radio>
                        <el-radio :label="3">医保</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="启/停" class="switch-box">
                    <el-switch v-model="editForm.status"></el-switch>
                </el-form-item>
                <el-form-item label="模块权限" class="form-auth">
                    <el-tree
                        :data="authObj"
                        show-checkbox
                        node-key="id"
                        ref="tree"
                        :default-checked-keys="rolesList"
                        highlight-current>
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog" size="small">取 消</el-button>
                <el-button type="primary" @click="submitEditForm('dialogForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {getAuthList, changeState, addRole, editRole} from '@/api/system/auth'
    import {getSortString, showBtnAuth} from '@/utils/filters'
    import permission from '@/assets/json/permission.json'
    import Pagination from '@/components/Pagination'

    export default {
        name: 'index',
        data () {
            return {
                // 搜索条件
                searchForm: {
                    mechanism: '',
                    name: ''
                },
                // 当前机构
                nowOrgid: '',
                // 机构列表
                mechanismList: [],
                // 科室列表
                departmentList: [],
                // 表格数据
                tableData: [],
                // 数据总数
                total: 1,
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 10,
                // 表格高度
                tableHeight: 100,
                // 显示弹框
                dialogVisible: false,
                // 编辑表单
                editForm: {
                    name: '',
                    type: '',
                    status: true
                },
                // 当前展开
                activeName: 'system',
                // 是否是新增
                isAdd: true,
                // 编辑所拥有权限
                rolesList: [],
                // 权限列表json
                authObj: {},
                // 用户拥有权限
                userAuth: [],
                // 排序方式
                orderBy: null,
                // 排序字段
                sortMap: {},
                // 所有子级目录
                allLastChild: [],
                // 初次默认用户机构（可用/判断过是否存在）
                defaultMId: '',
                editFormRules: {
                    name: [
                        {required: true, message: '请填写名称', trigger: ['blur', 'change']}
                    ],
                    type: [
                        {required: true, message: '请选择类型', trigger: 'change'}
                    ]
                },
                // 使用储存的数据，不去请求
                useStore: false
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5
            this.tableHeight = height > 107 ? height : 107
            this.userAuth = JSON.parse(localStorage.getItem('rolesCode'))
            this.getMechanismList()
            this.initData()
            this.getData()
            this.getLastChild()
            Array.from(new Set(this.allLastChild))
        },
        mounted () {
            window.onresize = () => {
                // 213=其他元素高度60+50+48+55 10=距离底部边距 78=分页组件高度 5=适应性调整
                let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5
                this.tableHeight = height > 107 ? height : 107
            }
        },
        methods: {
            showBtnAuth,
            /**
             * 初始化页面参数
             */
            initData () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (JSON.stringify(query) !== '{}') {
                    this.searchForm.mechanism = query.orgId
                    this.searchForm.name = query.keyword
                    this.currentPage = query.index || 1
                    this.pageSize = query.pageSize || 10
                    this.orderBy = query.orderBy || null
                }
            },
            /**
             * 获取机构列表
             */
            getMechanismList () {
                let mechanismList = this.getLocalStorage('userInfo', 'mechanism')
                let parentList = []
                mechanismList.forEach(item => {
                    // 一级机构
                    if (!item.pid) {
                        parentList.push({
                            value: item.id,
                            label: item.name,
                            children: []
                        })
                        // 有一级机构的二级机构
                        mechanismList.forEach(it => {
                            if (it.pid === item.id) {
                                parentList[parentList.length - 1].children.push({
                                    value: it.id,
                                    label: it.name,
                                    children: null
                                })
                            }
                        })
                        if (!parentList[parentList.length - 1].children.length) {
                            parentList[parentList.length - 1].children = null
                        }
                    } else {
                        // 二级机构
                        let parent = mechanismList.filter(i => item.pid === i.id)
                        if (!parent.length) {
                            parentList.push({
                                value: item.id,
                                label: item.name,
                                children: null
                            })
                        }
                    }
                })
                this.mechanismList = parentList
                if (this.mechanismList.length) {
                    if (this.getLocalStorage('userMechanism', 'id') && this.hasMechanismId(this.getLocalStorage('userMechanism', 'id'))) {
                        this.searchForm.mechanism = this.getLocalStorage('userMechanism', 'id')
                    } else {
                        this.searchForm.mechanism = parentList[0].value
                    }
                }
                this.defaultMId = this.searchForm.mechanism
            },
            /**
             * 判断所属机构是否在组织机构中
             * @param id 所属机构id
             */
            hasMechanismId (id) {
                let res = this.mechanismList.filter(item => item.value === id)
                return res.length !== 0
            },
            /**
             * 判断当前机构是否是系统机构
             */
            checkOrg () {
                let mechanismList = this.getLocalStorage('userInfo', 'mechanism')
                let res = mechanismList.filter(item => item.id === this.nowOrgid)
                return res[0].name === '系统机构'
            },
            /**
             * 初始化权限数组
             */
            initAuthTree () {
                this.authObj = []
                let allAuth = []
                Object.keys(permission).forEach(key => {
                    allAuth.push(permission[key])
                })
                // 一级菜单无父级id
                this.authObj = this.traverseArray(allAuth, 0)
            },
            /**
             * 遍历数组组装数据
             * @param arr 遍历的数组
             * @param parentId 该数组的父级id
             */
            traverseArray (arr, parentId) {
                let res = []
                let authArr = JSON.parse(localStorage.getItem('rolesCode'))
                if (authArr.includes(100003000000)) {
                    authArr.push(999999999999)
                }
                arr.forEach(item => {
                    if (this.isAdd) {
                        if (authArr.includes(item.code)) {
                            // 不开放给用户的菜单code
                            if (!(!this.checkOrg() && [300001000000, 300008000000, 300009000000, 300005001000, 300006002000, 300006001000, 300006000000].includes(item.code))) {
                                let attributes = {
                                    id: item.code,
                                    label: item.name,
                                    parentId: parentId
                                }
                                if (item.children) {
                                    attributes.children = this.traverseArray(item.children, item.code)
                                }
                                res.push(attributes)
                            }
                        }
                    } else {
                        let attributes = {
                            id: item.code,
                            label: item.name,
                            disabled: !authArr.includes(item.code)
                        }
                        if (item.children) {
                            attributes.children = this.traverseArray(item.children, item.code)
                        }
                        res.push(attributes)
                    }
                })
                return res
            },
            /**
             * 获取最后一级id
             */
            getLastChild () {
                let allAuth = []
                Object.keys(permission).forEach(key => {
                    allAuth.push(permission[key])
                })
                this.traverseLastChild(allAuth)
            },
            /**
             * 遍历最后一级
             * @param allAuth 所有权限
             */
            traverseLastChild (allAuth) {
                allAuth.forEach(item => {
                    if (item.children) {
                        this.traverseLastChild(item.children)
                    } else {
                        this.allLastChild.push(item.code)
                    }
                })
            },
            /**
             * 修改条件后从第一页开始
             */
            toFirstPage () {
                this.currentPage = 1
                this.getData()
            },
            /**
             * 获取表格数据
             * @param type 是否重置页码
             */
            getData (type) {
                let params = {
                    orgId: this.searchForm.mechanism,
                    keyword: this.searchForm.name,
                    index: this.currentPage,
                    pageSize: this.pageSize,
                    orderBy: this.orderBy
                }
                this.nowOrgid = this.searchForm.mechanism
                this.setGetStore(this.$route.name, params)
                if (this.getSession(this.$route.name, 'getAuthList') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getAuthList')
                    if (res.code.toString() === '200') {
                        this.tableData = res.data.rows
                        this.sortMap = res.data.maps
                        this.total = res.data.total
                    }
                } else {
                    getAuthList(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getAuthList: res})
                        if (res.code.toString() === '200') {
                            this.tableData = res.data.rows
                            this.sortMap = res.data.maps
                            this.total = res.data.total
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 排序修改
             * @param colData.prop 排序参数
             * @param colData.order 正序倒序 ascending 升序 descending 降序 null 不排序默认
             */
            sortChange (colData) {
                this.orderBy = getSortString(colData, this.sortMap)
                this.tableData = []
                this.currentPage = 1
                this.toFirstPage()
            },
            /**
             * 启动停止
             * @param index 索引
             * @param row 行数据
             */
            toChangeState (index, row) {
                let text = ''
                let title = ''
                if (row.state) {
                    text = `您确定启用"${row.name}"角色吗?`
                    title = '启用角色'
                } else {
                    text = `您确定停用"${row.name}"角色吗?停用后将不能再被使用!`
                    title = '停用角色'
                }
                this.$confirm(text, title, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    this.changeIdState(row.id, row.state)
                }).catch(() => {
                    row.state = !row.state
                })
            },
            /**
             * 改变指定状态
             * @param id 数据id
             * @param state 状态
             */
            changeIdState (id, state) {
                let params = {
                    id: id,
                    state: state
                }
                changeState(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$message.success(state ? '启用成功' : '停用成功')
                    } else if (res.code.toString() === '404') {
                        this.$message.error('未找到该职务')
                    } else {
                        this.$message.error(res.message)
                    }
                    this.getData()
                })
            },
            /**
             * 编辑表格内容
             * @param row 行数据
             */
            tableEdit (row) {
                this.isAdd = false
                this.editForm = {
                    name: row.name,
                    status: row.state,
                    type: row.roleType,
                    id: row.id
                }
                this.rolesList = []
                row.powerID.forEach(item => {
                    if (this.allLastChild.includes(parseInt(item))) {
                        this.rolesList.push(parseInt(item))
                    }
                })
                this.initAuthTree()
                this.dialogVisible = true
            },
            /**
             * 关闭弹框
             */
            closeDialog () {
                this.editForm = {
                    name: '',
                    type: '',
                    status: true
                }
                this.rolesList = []
                this.$refs.tree.setCheckedKeys([])
                this.authObj = []
                this.$refs['dialogForm'].resetFields()
                this.dialogVisible = false
            },
            /**
             * 点击新增打开弹窗
             */
            showAddDialog () {
                this.isAdd = true
                this.initAuthTree()
                this.rolesList = []
                this.dialogVisible = true
            },
            /**
             * 提交编辑
             * @param formName 表单名
             */
            submitEditForm (formName) {
                let updateAuth = Array.from(new Set([].concat(this.$refs.tree.getCheckedKeys(), this.$refs.tree.getHalfCheckedKeys())))
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let params = {
                            orgId: this.searchForm.mechanism,
                            name: this.editForm.name,
                            powerID: updateAuth.join(',').split(','),
                            roleType: this.editForm.type,
                            state: this.editForm.status
                        }
                        if (params.powerID.indexOf('999999999999') > -1) {
                            params.powerID.splice(params.powerID.indexOf('999999999999'), 1)
                        }
                        if (this.isAdd) {
                            if (updateAuth.length) {
                                addRole(params).then(res => {
                                    if (res.code.toString() === '200') {
                                        this.$message.success('新增成功')
                                        this.closeDialog()
                                        this.getData()
                                    } else {
                                        this.$message.error(res.message)
                                    }
                                })
                            } else {
                                this.$message.warning('新增角色请至少选择一个权限')
                            }
                        } else {
                            params.id = this.editForm.id
                            editRole(params).then(res => {
                                if (res.code.toString() === '200') {
                                    this.$message.success('保存成功')
                                    this.closeDialog()
                                    this.getData()
                                } else {
                                    this.$message.error(res.message)
                                }
                            })
                        }
                    } else {
                        return false
                    }
                })
            }
        },
        components: {
            Pagination
        },
        beforeDestroy () {
            window.onresize = null
        }
    }
</script>

<style lang="scss" scoped>
    .system-auth-container {
        .system-search-form {
            .el-form-item {
                margin-bottom: 0;
            }
        }
        .table-box {
            background: #fff;
            padding: 10px;
            box-sizing: border-box;
            height: calc(100vh - 183px);
            .add-btn {
                margin-bottom: 10px;
            }
        }
        /deep/.el-dialog {
            width: 800px!important;
            margin-top: 6vh!important;
            .el-dialog__body {
                padding: 10px;
                .dialog-form {
                    width: 90%;
                    overflow-x: hidden;
                    margin: 0 auto;
                    max-height: 600px;
                    overflow-y: auto;
                }
                .form-auth {
                    width: 100%;
                    .el-form-item__content {
                        width: calc(100% - 80px);
                    }
                }
            }
            .el-dialog__footer {
                text-align: right;
            }
        }
        .item-back {
            margin-left: 30px;
        }
        .item-checkbox {
            margin-left: 30px;
        }
        .checkbox-child {
            margin-left: 60px;
        }
    }
</style>
